import 'dart:io';
import 'package:basic/basic.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../http/base_http.dart';

//处理异常的帮助类
class ExceptionHelper {
  static bool debugMode = false; //是否打印日志
  static String sNoNetworkLinkTips = '网络连接不可用,请稍后重试'; //无网络提示语
  static String sExceptionTips = '网络繁忙,请稍后再试'; //网络异常提示语

  static void init({
    bool isDebug = false,
    String? noNetworkLinkTips,
    String? exceptionTips,
  }) {
    debugMode = isDebug;
    if (noNetworkLinkTips != null) sNoNetworkLinkTips = noNetworkLinkTips;
    if (exceptionTips != null) sExceptionTips = exceptionTips;
  }

  //捕捉全部error异常
  static catchError(
    dynamic e, {
    StackTrace? stackTrace,
    bool toast = true,
  }) async {
    if (e is Exception && e is DioException) {
      catchDioError(e, stackTrace: stackTrace, toast: toast);
    } else {
      ToastUtil.show(msg: sExceptionTips);
    }
    printErrorStack(e, stackTrace);
  }

  //捕捉DioError异常
  static catchDioError(
    DioException dioError, {
    StackTrace? stackTrace,
    bool toast = true,
  }) async {
    if (dioError.error is ApiException) {
      if (toast)
        ToastUtil.show(msg: (dioError.error as ApiException).message ?? "");
    } else if (dioError.error is SocketException) {
      ToastUtil.show(msg: sNoNetworkLinkTips);
    } else {
      ToastUtil.show(msg: sExceptionTips);
    }
  }

  //是否是 DioError 异常
  static bool isDioError(dynamic e) {
    return e != null && e is DioError;
  }

  //是否接口异常
  static bool isNotSuccess(dynamic e) {
    return e != null && e is DioError && e.error is ApiException;
  }
}

/// [e]为错误类型 :可能为 Error , Exception ,String
/// [s]为堆栈信息
printErrorStack(e, s) {
  if (!ExceptionHelper.debugMode) return;
  LogUtil.e('<-----↑↑↑↑↑↑↑↑↑↑-----$e-----↑↑↑↑↑↑↑↑↑↑----->');
  if (s != null) debugPrintStack(stackTrace: s);
}
